/*
 * Copyright 2009 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.google.appengine.demos.oauth;

import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Display JSP pages associated with the OAuth contacts fetcher.
 */
public class ContactsTemplates {
  private static final Logger logger = Logger.getLogger(ContactsTemplates.class.getName());

  /**
   * Display JSP pages for the contacts fetcher application.
   */
  public static void showContactsPage(HttpServletRequest req, HttpServletResponse resp,
      OAuthFetchResponse oauthResponse, String jspName) throws IOException, ServletException {
    UserService userService = UserServiceFactory.getUserService();
    req.setAttribute("logout", userService.createLogoutURL("/"));
    
    if (oauthResponse.getOAuthError() != null) {
      req.setAttribute("error_code", oauthResponse.getOAuthError());
    }
    
    if (oauthResponse.getOAuthErrorText() != null) {
      req.setAttribute("error_text", oauthResponse.getOAuthErrorText());
    }
    
    if (oauthResponse.getOAuthApprovalUrl() != null) {
      req.setAttribute("approval_url", oauthResponse.getOAuthApprovalUrl());
    }
    
    String contacts = new String(oauthResponse.getResponse().getContent(), "UTF-8");
    try {
      req.setAttribute("contacts", parseContacts(contacts));
    } catch (Exception e) {
      req.setAttribute("all_data", contacts);
      logger.log(Level.SEVERE, "Unable to parse contacts '%s'" + contacts, e);
    }
    RequestDispatcher dispatcher = req.getRequestDispatcher(jspName);
    dispatcher.forward(req, resp);
  }
  
  /**
   * Parse portable contacts response.  May throw a RuntimeException if the response is malformed.
   */
  private static List<Map<String, String>> parseContacts(String contacts) {
    List<Map<String, String>> out = new ArrayList<Map<String, String>>();
    JsonParser parser = new JsonParser();
    JsonObject contactsJson = parser.parse(contacts).getAsJsonObject();
    for (JsonElement entry : contactsJson.getAsJsonArray("entry")) {
      JsonObject contact = entry.getAsJsonObject();
      if (contact.has("emails") && contact.has("displayName")) {
        JsonObject emailObject = contact.getAsJsonArray("emails").get(0).getAsJsonObject();
        String email = emailObject.get("value").getAsString();
        String displayName = contact.getAsJsonPrimitive("displayName").getAsString();
        Map<String, String> contactTemplate = new HashMap<String, String>();
        contactTemplate.put("email", email);
        contactTemplate.put("name", displayName);
        out.add(contactTemplate);
      }
    }
    return out;
  }

  /**
   * Mark a response as uncacheable.
   */
  public static void setNoCache(HttpServletResponse resp) {
    resp.setHeader("Cache-Control", "no-cache, must-revalidate");
    resp.setHeader("Pragma", "no-cache");
    resp.setHeader("Expires", "Fri, 01 Jan 1990 00:00:00 GMT");
  }
  
}
